package net.oschina.esb.core;

import net.oschina.esb.EsbConfigKey;
import net.oschina.esb.core.env.EsbContext;
import net.oschina.esb.util.ConvertUtil;
import net.oschina.esb.util.DnsUtil;
import net.oschina.esb.util.JsonUtil;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.core.type.AnnotationMetadata;

import java.util.List;
import java.util.Map;

/**
 * 注册自定义 DNS
 *
 * @author Arvin
 * @time 2018/5/6 15:45
 */
@Configuration
public class CustomDnsRegister extends AbstractSpringBootRegister {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry, Environment environment, ApplicationContext applicationContext) {
        try {
            String enabledString = EsbContext.getAppProperty(environment, EsbConfigKey.SWITCH_DNS_CUSTOM, "false");

            boolean enabled = ConvertUtil.toBoolean(enabledString, false);

            if (enabled) {


                Resource resource = EsbContext.getDnsHostResource();

                if (null != resource && resource.exists()) {
                    logger.info("开启了自定义DNS， hosts文件： " + resource.getURI());
                    Map<String, List<String>> dnsMap = DnsUtil.loadCustomDns(resource.getInputStream());

                    logger.info("成功加载了自定义的DNS，加载的配置包含： " + JsonUtil.toJson(dnsMap));
                } else {
                    logger.info("没有搜索到自定的DNS HOSTS 文件！");
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("加载自定义DNS配置出错： " + e.getMessage(), e);
        }
    }
}
